package com.quanyan.orderpay.web.filter;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.user.AppUserCacheInfo;
import com.quanyan.common.utils.HttpServletRequestWrapper;
import com.quanyan.common.utils.MD5Utils;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;


/**
 * @Author Hugo.Wwg
 * @Since 2016-06-02
 */
@Component
public class CommonFilter implements Filter {

    @Autowired
    private RedisTemplate redisTemplate;
    private static final Logger logger = LoggerFactory.getLogger(CommonFilter.class);



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    private void ajaxError(ApiResponseEnum apiResponseEnum, ServletResponse response)
            throws IOException {
        response.getWriter().write(JSON.toJSON(APIResponse.returnFail(apiResponseEnum)).toString());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        long startTime = System.currentTimeMillis();
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String uri = request.getRequestURI();
        String sessionId = request.getHeader("userCookiesName");
        RedisKey redisKey = new RedisKey(sessionId, "");

        AppUserCacheInfo appUserCacheInfo = (AppUserCacheInfo)
                redisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);
        if (appUserCacheInfo != null) {
            Integer userId = appUserCacheInfo.getUser_id();
            if (userId != null && userId.intValue()>0) {
                //userId 不为 null 表示已经登录
                request.setAttribute("uid", userId);
            }
        }
        if (uri.startsWith("/admin/api/orderpay/withdraw")) {
            String sign = request.getHeader("sign");
            ServletRequest requestWrapper = new HttpServletRequestWrapper(request);

            String reqData = getBodyString(requestWrapper.getReader(), uri);
            logger.warn("CommonFilter读取body中的参数: " + reqData);
            if (reqData == null) {
                ajaxError(ApiResponseEnum.ILLEGAL_PROTOCOL, response);
                return;
            }
            String md5Sign = MD5Utils.MD5Encode(reqData + Constants.SECRET_KEY);
            if (!sign.equals(md5Sign)) {
                ajaxError(ApiResponseEnum.ILLEGAL_PROTOCOL, response);
            }
        }else {
            chain.doFilter(request, response);
        }
    }


    private static String getBodyString(BufferedReader br, String reqUrl) {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (IOException e) {
            logger.warn("requestUrl: " + reqUrl + ", Request error: "
                    + e.getMessage() + "Request URI: ");

        }
        return str;
    }
}
